// src/components/racing/VehicleList.jsx
import React, { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { getItem } from '../../utils/localStorage';
import { useApp } from '../../contexts/AppContext';
import { useAuth } from '../../contexts/AuthContext';

const VehicleList = () => {
  const [vehicles, setVehicles] = useState([]);
  const navigate = useNavigate();
  const { selectedTrack, setSelectedVehicle } = useApp();
  const { user } = useAuth();

  useEffect(() => {
    if (!user) {
      navigate('/login');
      return;
    }
    
    if (!selectedTrack) {
      navigate('/');
      return;
    }

    const storedVehicles = JSON.parse(getItem('vehicles') || '[]');
    setVehicles(storedVehicles);
  }, [user, selectedTrack, navigate]);

  const handleSelectVehicle = (vehicle) => {
    setSelectedVehicle(vehicle);
    navigate('/payment');
  };

  return (
    <div className="space-y-6">
      <h1 className="text-2xl font-bold text-gray-900">选择赛车</h1>
      <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
        {vehicles.map((vehicle) => (
          <div
            key={vehicle.id}
            className="bg-white rounded-lg shadow-md overflow-hidden"
          >
            <div className="aspect-w-16 aspect-h-9">
              <img
                src={vehicle.image}
                alt={vehicle.name}
                className="w-full h-48 object-cover"
              />
            </div>
            <div className="p-4">
              <h2 className="text-xl font-semibold text-gray-900">
                {vehicle.name}
              </h2>
              <p className="mt-2 text-gray-600">{vehicle.description}</p>
              <div className="mt-4 flex justify-between items-center">
                <span className="text-xl font-bold text-blue-600">
                  ¥{vehicle.price}/小时
                </span>
                <button
                  onClick={() => handleSelectVehicle(vehicle)}
                  className="bg-blue-600 text-white px-4 py-2 rounded-md hover:bg-blue-700"
                >
                  选择
                </button>
              </div>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
};

export default VehicleList;